package com.bolingcavalry.crm.message.service;

import com.aliyun.auth.credentials.utils.AuthUtils;
import com.base.Status;
import com.bolingcavalry.crm.WeChatPush.service.WeChatPushService;
import com.bolingcavalry.crm.message.config.RabbitMQConstants;
import com.bolingcavalry.crm.message.service.MessageService;
import com.bolingcavalry.crm.security.utils.SecurityUtils;
import com.bolingcavalry.crm.user.mapper.UserMapper;
import com.bolingcavalry.crm.utils.AUtils;
import com.dto.MessageCreateDTO;
import com.dto.TaskReviewMessageDTO;
import com.entity.message.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用消费者：处理所有部门的任务单下推审核通知
 * 根据消息中携带的 roleId，生成对应角色负责人的待办消息
 */
@Component
@Slf4j
public class TaskOrderReviewConsumer {

    @Autowired
    private MessageService messageService;

    @Autowired
    private AUtils aUtils;

    // 注入微信推送服务
    @Autowired
    private WeChatPushService weChatPushService;

    // 注入用户Mapper用于获取openid
    @Autowired
    private UserMapper userMapper;

    /**
     * 监听所有任务订单的队列（它们都发送结构相似的消息）
     * 使用 @RabbitListener 监听多个队列
     * 任务审核
     */
    @RabbitListener(
            queues = {RabbitMQConstants.QUEUE_TASK_ORDER,}
    )
    public void handleTaskOrderMessage(TaskReviewMessageDTO taskReviewMessageDTO) {
        log.info("监听到消息: " + taskReviewMessageDTO);
        try {
            // 从消息中提取关键字段
            String orderNumber =  taskReviewMessageDTO.getOrderNumber();
            String title =  taskReviewMessageDTO.getTitle();
            String content =  taskReviewMessageDTO.getContent();
            String businessType =  taskReviewMessageDTO.getBusinessType();
            String RoleName = taskReviewMessageDTO.getRoleName();
            Long orderId =  taskReviewMessageDTO.getOrderId();
            String senderName =  taskReviewMessageDTO.getSenderName();
            //关联人id
            Long relatedId =  taskReviewMessageDTO.getRelatedId();

            System.out.println("📨 正在处理审核消息: 订单号=" + orderNumber + ", 需通知角色=" + RoleName);
            // 为每个负责人生成一条待办消息
            MessageCreateDTO dto = new MessageCreateDTO();
            dto.setTitle(title);
            dto.setContent(content);
            dto.setMessageType("processing");
            dto.setBusinessType(businessType);
            dto.setOrderNumber(orderNumber);
            dto.setRoleName(RoleName);
            dto.setRoleId(aUtils.getRoleIdByRoleName(RoleName));
            dto.setRelatedId(relatedId);
            dto.setSenderName(senderName);
            dto.setSource("SYSTEM");
            dto.setStatus(Status.MESSAGE_STATUS_UNTREATED);

            // 保存消息到数据库
            Message message = messageService.createMessage(dto);

            System.out.println("✅ 已生成审批消息: 角色=" + RoleName +
                    ", 订单号=" + orderNumber);

            // 推送微信消息
            pushWeChatMessage(taskReviewMessageDTO, message);

        } catch (Exception e) {
            System.err.println("❌ 处理审核消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 监听总结订单的队列
     * 完结审核
     */
    @RabbitListener(queues = {RabbitMQConstants.QUEUE_SUMMARY_ORDER})
    public void handleSummaryOrderMessage(TaskReviewMessageDTO taskReviewMessageDTO) {
        log.info("监听到消息: " + taskReviewMessageDTO);
        try {
            // 从消息中提取关键字段
            String orderNumber =  taskReviewMessageDTO.getOrderNumber();
            String title =  taskReviewMessageDTO.getTitle();
            String content =  taskReviewMessageDTO.getContent();
            String businessType =  taskReviewMessageDTO.getBusinessType();
            String RoleName = taskReviewMessageDTO.getRoleName();
            Long orderId =  taskReviewMessageDTO.getOrderId();
            String senderName =  taskReviewMessageDTO.getSenderName();
            Long receiverId =  taskReviewMessageDTO.getReceiverId();

            System.out.println("📨 正在处理审核消息: 订单号=" + orderNumber + ", 需通知角色=" + RoleName);

            MessageCreateDTO dto = new MessageCreateDTO();
            dto.setTitle(title);
            dto.setContent(content);
            dto.setMessageType("processing");
            dto.setBusinessType(businessType);
            dto.setOrderNumber(orderNumber);
            dto.setRoleName(RoleName);
            dto.setRoleId(aUtils.getRoleIdByRoleName(RoleName));
            dto.setSenderName(senderName);
            dto.setSource("SYSTEM");
            dto.setReceiverId(receiverId);
            dto.setStatus(Status.MESSAGE_STATUS_UNTREATED);

            // 保存消息到数据库
            Message message = messageService.createMessage(dto);

            System.out.println("✅ 已生成审批消息: 角色=" + RoleName +
                    ", 订单号=" + orderNumber);

            // 推送微信消息
            pushWeChatMessage(taskReviewMessageDTO, message);

        } catch (Exception e) {
            System.err.println("❌ 处理审核消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 服务问题通知
     */
    @RabbitListener(queues = {RabbitMQConstants.QUEUE_SERVICE_PROBLEM})
    public void handleServiceProblemMessage(TaskReviewMessageDTO taskReviewMessageDTO) {
        log.info("监听到消息: " + taskReviewMessageDTO);
        try {
            // 从消息中提取关键字段
            String orderNumber =  taskReviewMessageDTO.getOrderNumber();
            Long serviceProblemId =  taskReviewMessageDTO.getServiceProblemId();
            String title =  taskReviewMessageDTO.getTitle();
            String content =  taskReviewMessageDTO.getContent();
            String businessType =  taskReviewMessageDTO.getBusinessType();
            String RoleName = taskReviewMessageDTO.getRoleName();
            Long orderId =  taskReviewMessageDTO.getOrderId();
            String senderName =  taskReviewMessageDTO.getSenderName();
            Long receiverId =  taskReviewMessageDTO.getReceiverId();

            System.out.println("📨 正在处理审核消息: 订单号=" + orderNumber + ", 需通知角色=" + RoleName);

            MessageCreateDTO dto = new MessageCreateDTO();
            dto.setTitle(title);
            dto.setContent(content);
            dto.setMessageType("notices");
            dto.setBusinessType(businessType);
            dto.setOrderNumber(orderNumber);
            dto.setServiceProblemId(serviceProblemId);
            dto.setRoleName(RoleName);
            dto.setRoleId(aUtils.getRoleIdByRoleName(RoleName));
            dto.setSenderName(senderName);
            dto.setSource("SYSTEM");
            dto.setReceiverId(receiverId);
            dto.setStatus(Status.MESSAGE_STATUS_UNTREATED);

            // 保存消息到数据库
            Message message = messageService.createMessage(dto);

            System.out.println("✅ 已生成审批消息: 角色=" + RoleName +
                    ", 订单号=" + orderNumber);

            // 推送微信消息
            pushWeChatMessage(taskReviewMessageDTO, message);

        } catch (Exception e) {
            System.err.println("❌ 处理审核消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 通知
     */
    @RabbitListener(queues = {RabbitMQConstants.QUEUE_NOTIFY_COMMANDER})
    public void handleNotifyCommanderMessage(TaskReviewMessageDTO taskReviewMessageDTO) {
        log.info("监听到消息: " + taskReviewMessageDTO);
        try {
            // 从消息中提取关键字段
            String orderNumber =  taskReviewMessageDTO.getOrderNumber();
            String title =  taskReviewMessageDTO.getTitle();
            String content =  taskReviewMessageDTO.getContent();
            String businessType =  taskReviewMessageDTO.getBusinessType();
            String RoleName = taskReviewMessageDTO.getRoleName();
            Long orderId =  taskReviewMessageDTO.getOrderId();
            String senderName =  taskReviewMessageDTO.getSenderName();
            Long receiverId =  taskReviewMessageDTO.getReceiverId();

            System.out.println("📨 正在处理审核消息: 订单号=" + orderNumber + ", 需通知角色=" + RoleName);

            MessageCreateDTO dto = new MessageCreateDTO();
            dto.setTitle(title);
            dto.setContent(content);
            dto.setMessageType("notices");
            dto.setBusinessType(businessType);
            dto.setOrderNumber(orderNumber);
            dto.setRoleName(RoleName);
            dto.setRoleId(aUtils.getRoleIdByRoleName(RoleName));
            dto.setSenderName(senderName);
            dto.setSource("SYSTEM");
            dto.setReceiverId(receiverId);
            dto.setStatus(Status.MESSAGE_STATUS_UNTREATED);

            // 保存消息到数据库
            Message message = messageService.createMessage(dto);

            System.out.println("✅ 已生成审批消息: 角色=" + RoleName +
                    ", 订单号=" + orderNumber);

            // 推送微信消息
            pushWeChatMessage(taskReviewMessageDTO, message);

        } catch (Exception e) {
            System.err.println("❌ 处理审核消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 监听拒绝通知
     */
    @RabbitListener(queues = {RabbitMQConstants.QUEUE_REFUSE_NOTIFY})
    public void handleRefuseNotifyMessage(TaskReviewMessageDTO taskReviewMessageDTO) {
        log.info("监听到消息: " + taskReviewMessageDTO);
        try {
            // 从消息中提取关键字段
            String orderNumber =  taskReviewMessageDTO.getOrderNumber();
            String title =  taskReviewMessageDTO.getTitle();
            if(taskReviewMessageDTO.getContent()== null){
                taskReviewMessageDTO.setContent("无");
            }
            String content =  taskReviewMessageDTO.getContent();
            String businessType =  taskReviewMessageDTO.getBusinessType();
            String RoleName = taskReviewMessageDTO.getRoleName();
            Long orderId =  taskReviewMessageDTO.getOrderId();
            String senderName =  taskReviewMessageDTO.getSenderName();
            Long receiverId =  taskReviewMessageDTO.getReceiverId();

            System.out.println("📨 正在处理审核消息: 订单号=" + orderNumber + ", 需通知角色=" + RoleName);

            MessageCreateDTO message1 = new MessageCreateDTO();
            message1.setTitle(title);
            message1.setContent(content);
            message1.setMessageType("notices");
            message1.setBusinessType(businessType);
            message1.setOrderNumber(orderNumber);
            message1.setSenderName(senderName);
            message1.setReceiverId(receiverId);
            message1.setStatus(Status.MESSAGE_STATUS_UNTREATED);

            // 保存消息到数据库
            Message message = messageService.createMessage(message1);

            // 推送微信消息
            pushWeChatMessage(taskReviewMessageDTO, message);

        } catch (Exception e) {
            System.err.println("❌ 处理审核消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 推送微信消息的通用方法
     */
    private void pushWeChatMessage(TaskReviewMessageDTO taskReviewMessageDTO, Message message) {
        try {
            // 获取目标用户openid列表
            List<String> openidList = getTargetOpenids(taskReviewMessageDTO);

            if (CollectionUtils.isEmpty(openidList)) {
                log.warn("未找到目标用户，消息ID: {}", message.getId());
                return;
            }

            // 为每个用户推送消息
            for (String openid : openidList) {
                try {
                    // 调用微信推送服务
                    weChatPushService.pushMessageByMessageType(openid, taskReviewMessageDTO);
                    log.info("微信消息推送成功，用户openid: {}, 消息ID: {}", openid, message.getId());
                } catch (Exception e) {
                    log.error("推送微信消息失败，用户openid: {}, 消息ID: {}, 错误: {}",
                            openid, message.getId(), e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("获取目标用户失败，消息ID: {}, 错误: {}", message.getId(), e.getMessage());
        }
    }

    /**
     * 获取目标用户openid列表
     */
    private List<String> getTargetOpenids(TaskReviewMessageDTO dto) {
        List<String> openidList = new ArrayList<>();

        // 如果指定了接收人ID，推送给该用户
        if (dto.getReceiverId() != null) {
            String openid = userMapper.selectOpenidByUserId(dto.getReceiverId());
            if (openid != null && !openid.isEmpty()) {
                openidList.add(openid);
            }
        }
        // 如果指定了角色，推送给该角色的所有用户
        else if (dto.getRoleName() != null && !dto.getRoleName().isEmpty()) {
            Long roleId = aUtils.getRoleIdByRoleName(dto.getRoleName());
            if (roleId != null) {
                List<String> roleOpenids = userMapper.selectOpenidsByRoleId(roleId);
                if (!CollectionUtils.isEmpty(roleOpenids)) {
                    openidList.addAll(roleOpenids);
                }
            }
        }

        return openidList;
    }
}